<template>
  <view class="style-list-container">
    <!-- 搜索栏 -->
    <view class="search-bar">
      <view class="search-input-wrapper">
        <text class="search-icon">🔍</text>
        <input 
          class="search-input" 
          type="text" 
          placeholder="搜索风格名称或标签" 
          v-model="searchQuery"
          @input="onSearchInput"
        />
        <text class="clear-icon" v-if="searchQuery" @click="clearSearch">✕</text>
      </view>
    </view>
    
    <!-- 分类标签 -->
    <scroll-view class="category-scroll" scroll-x="true" show-scrollbar="false">
      <view class="category-list">
        <view 
          class="category-item" 
          :class="{ active: activeCategory === 'all' }"
          @click="selectCategory('all')"
        >
          全部
        </view>
        <view 
          class="category-item" 
          v-for="(category, index) in categories" 
          :key="index"
          :class="{ active: activeCategory === category.id }"
          @click="selectCategory(category.id)"
        >
          {{ category.name }}
        </view>
      </view>
    </scroll-view>
    
    <!-- 风格列表 -->
    <view class="styles-grid" v-if="filteredStyles.length > 0">
      <view 
        class="style-item" 
        v-for="(style, index) in filteredStyles" 
        :key="index"
        @click="goToStyleDetail(style.id)"
      >
        <image class="style-image" :src="style.previewImage" mode="aspectFill"></image>
        <view class="style-info">
          <view class="style-name">{{ style.name }}</view>
          <view class="style-tags">
            <!-- 由于后端数据中没有tags字段，这里显示分类信息 -->
            <view class="style-tag">
              {{ getCategoryName(style.category) }}
            </view>
          </view>
          <view class="style-stats">
            <view class="stat-item">
              <text class="stat-icon">👁️</text>
              <text class="stat-value">{{ formatNumber(style.useCount || 0) }}</text>
            </view>
            <view class="stat-item">
              <text class="stat-icon">❤️</text>
              <text class="stat-value">{{ formatNumber(style.likeCount || 0) }}</text>
            </view>
          </view>
        </view>
      </view>
    </view>
    
    <!-- 空状态 -->
    <view class="empty-state" v-else>
      <image class="empty-image" src="/static/images/empty-search.png" mode="aspectFit"></image>
      <text class="empty-text">{{ isSearching ? '没有找到相关风格' : '暂无风格数据' }}</text>
      <button class="reset-button" v-if="isSearching" @click="resetSearch">重置搜索</button>
    </view>
    
    <!-- 加载更多 -->
    <view class="load-more" v-if="hasMore && filteredStyles.length > 0">
      <text class="load-more-text" @click="loadMore" v-if="!isLoading">加载更多</text>
      <text class="loading-text" v-else>加载中...</text>
    </view>
    
    <!-- 底部提示 -->
    <view class="bottom-tip" v-if="!hasMore && filteredStyles.length > 0">
      <text class="bottom-tip-text">— 已经到底啦 —</text>
    </view>
  </view>
</template>

<script>
import { styleApi } from '@/utils/api.js';

export default {
  data() {
    return {
      // 风格列表
      styleList: [],
      // 分类列表
      categories: [
        { id: 'popular', name: '热门' },
        { id: 'new', name: '最新' },
        { id: 'art', name: '艺术' },
        { id: 'photo', name: '照片' },
        { id: 'cartoon', name: '卡通' },
        { id: 'anime', name: '动漫' },
        { id: 'sketch', name: '素描' },
        { id: 'other', name: '其他' }
      ],
      // 当前选中的分类
      activeCategory: 'all',
      // 搜索关键词
      searchQuery: '',
      // 是否正在搜索
      isSearching: false,
      // 分页信息
      page: 1,
      pageSize: 20,
      hasMore: true,
      // 加载状态
      isLoading: false
    };
  },
  
  computed: {
    // 过滤后的风格列表
    filteredStyles() {
      let result = [...this.styleList];
      
      // 按分类过滤
      if (this.activeCategory !== 'all') {
        result = result.filter(style => {
          if (this.activeCategory === 'popular') {
            return style.isPopular;
          } else if (this.activeCategory === 'new') {
            // 30天内的新风格
            const thirtyDaysAgo = new Date();
            thirtyDaysAgo.setDate(thirtyDaysAgo.getDate() - 30);
            return new Date(style.createTime) >= thirtyDaysAgo;
          } else {
            return style.category === this.activeCategory;
          }
        });
      }
      
      // 按搜索关键词过滤
      if (this.searchQuery) {
        const query = this.searchQuery.toLowerCase();
        result = result.filter(style => {
          // 名称匹配
          if (style.name.toLowerCase().includes(query)) {
            return true;
          }
          
          // 标签匹配
          if (style.tags && style.tags.some(tag => tag.toLowerCase().includes(query))) {
            return true;
          }
          
          // 描述匹配
          if (style.description && style.description.toLowerCase().includes(query)) {
            return true;
          }
          
          return false;
        });
      }
      
      return result;
    }
  },
  
  onLoad(options) {
    // 如果有传入分类参数，则设置当前分类
    if (options.category) {
      this.activeCategory = options.category;
    }
    
    // 加载风格列表
    this.loadStyleList();
  },
  
  // 下拉刷新
  onPullDownRefresh() {
    this.page = 1;
    this.hasMore = true;
    this.loadStyleList(() => {
      uni.stopPullDownRefresh();
    });
  },
  
  // 触底加载更多
  onReachBottom() {
    if (this.hasMore && !this.isLoading) {
      this.loadMore();
    }
  },
  
  methods: {
    /**
     * 加载风格列表
     * @param {Function} callback - 回调函数
     */
    async loadStyleList(callback) {
      if (this.isLoading) return;
      
      this.isLoading = true;
      
      try {
        // 构建请求参数
        const params = {
          page: this.page,
          size: this.pageSize,
          orderBy: 'id', // 使用id字段排序，这是数据库中确定存在的字段
          orderType: 'desc' // 降序排序
        };
        
        // 添加分类参数
        if (this.activeCategory !== 'all') {
          params.category = this.activeCategory;
        }
        
        // 添加搜索参数
        if (this.searchQuery) {
          params.keyword = this.searchQuery;
        }
        
        // 调用API获取风格列表
        const result = await styleApi.getAllStyles(params);
        
        // 处理返回结果
        if (result && result.code === 200) {
          // 获取PageResponse对象
          const pageResponse = result.data || {};
          console.log(pageResponse);
          
          // 第一页时清空列表
          if (this.page === 1) {
            this.styleList = pageResponse.list || [];
          } else {
            // 追加数据
            this.styleList = [...this.styleList, ...(pageResponse.list || [])];
          }
          
          // 更新分页信息
          this.hasMore = pageResponse.hasNext || false;
          
          // 如果是搜索状态，则更新搜索状态
          this.isSearching = !!this.searchQuery;
        } else {
          uni.showToast({
            title: result.message || '加载风格列表失败',
            icon: 'none'
          });
        }
      } catch (error) {
        console.error('加载风格列表失败', error);
        uni.showToast({
          title: '加载风格列表失败',
          icon: 'none'
        });
      } finally {
        this.isLoading = false;
        
        // 执行回调
        if (typeof callback === 'function') {
          callback();
        }
      }
    },
    
    /**
     * 加载更多
     */
    loadMore() {
      this.page++;
      this.loadStyleList();
    },
    
    /**
     * 选择分类
     * @param {string} categoryId - 分类ID
     */
    selectCategory(categoryId) {
      if (this.activeCategory === categoryId) return;
      
      this.activeCategory = categoryId;
      this.page = 1;
      this.hasMore = true;
      this.loadStyleList();
    },
    
    /**
     * 搜索输入
     */
    onSearchInput() {
      // 防抖处理
      if (this.searchTimer) {
        clearTimeout(this.searchTimer);
      }
      
      this.searchTimer = setTimeout(() => {
        this.page = 1;
        this.hasMore = true;
        this.loadStyleList();
      }, 500);
    },
    
    /**
     * 清空搜索
     */
    clearSearch() {
      this.searchQuery = '';
      this.isSearching = false;
      this.page = 1;
      this.hasMore = true;
      this.loadStyleList();
    },
    
    /**
     * 重置搜索
     */
    resetSearch() {
      this.searchQuery = '';
      this.activeCategory = 'all';
      this.isSearching = false;
      this.page = 1;
      this.hasMore = true;
      this.loadStyleList();
    },
    
    /**
     * 跳转到风格详情
     * @param {number} styleId - 风格ID
     */
    goToStyleDetail(styleId) {
      uni.navigateTo({
        url: `/pages/style/style?id=${styleId}`
      });
    },
    
    /**
     * 格式化数字
     * @param {number} num - 数字
     * @returns {string} - 格式化后的字符串
     */
    formatNumber(num) {
      if (num >= 10000) {
        return (num / 10000).toFixed(1) + 'w';
      } else if (num >= 1000) {
        return (num / 1000).toFixed(1) + 'k';
      } else {
        return num.toString();
      }
    },
    
    /**
     * 获取分类名称
     * @param {string} categoryId - 分类ID
     * @returns {string} - 分类名称
     */
    getCategoryName(categoryId) {
      const category = this.categories.find(category => category.id === categoryId);
      return category ? category.name : '';
    }
  }
};
</script>

<style>
.style-list-container {
  min-height: 100vh;
  background-color: #f8f8f8;
  padding-bottom: 30rpx;
}

.search-bar {
  padding: 20rpx 30rpx;
  background-color: #fff;
  position: sticky;
  top: 0;
  z-index: 10;
}

.search-input-wrapper {
  display: flex;
  align-items: center;
  background-color: #f5f5f5;
  border-radius: 40rpx;
  padding: 10rpx 20rpx;
}

.search-icon {
  margin-right: 10rpx;
  color: #999;
}

.search-input {
  flex: 1;
  height: 60rpx;
  font-size: 28rpx;
}

.clear-icon {
  color: #999;
  padding: 0 10rpx;
}

.category-scroll {
  background-color: #fff;
  padding: 0 20rpx 20rpx;
  white-space: nowrap;
}

.category-list {
  display: inline-flex;
}

.category-item {
  padding: 10rpx 30rpx;
  margin-right: 20rpx;
  font-size: 28rpx;
  color: #666;
  background-color: #f5f5f5;
  border-radius: 30rpx;
}

.category-item.active {
  background-color: #FF69B4;
  color: #fff;
}

.styles-grid {
  padding: 20rpx;
  display: flex;
  flex-wrap: wrap;
  justify-content: space-between;
}

.style-item {
  width: 48%;
  margin-bottom: 30rpx;
  background-color: #fff;
  border-radius: 20rpx;
  overflow: hidden;
  box-shadow: 0 4rpx 20rpx rgba(0, 0, 0, 0.1);
}

.style-image {
  width: 100%;
  height: 300rpx;
}

.style-info {
  padding: 15rpx;
}

.style-name {
  font-size: 28rpx;
  font-weight: bold;
  color: #333;
  margin-bottom: 10rpx;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
}

.style-tags {
  display: flex;
  flex-wrap: wrap;
  margin-bottom: 15rpx;
}

.style-tag {
  font-size: 22rpx;
  color: #666;
  background-color: #f5f5f5;
  padding: 4rpx 12rpx;
  border-radius: 20rpx;
  margin-right: 10rpx;
  margin-bottom: 10rpx;
}

.style-tag.more {
  background-color: #f0f0f0;
  color: #999;
}

.style-stats {
  display: flex;
  justify-content: space-between;
}

.stat-item {
  display: flex;
  align-items: center;
}

.stat-icon {
  font-size: 24rpx;
  margin-right: 6rpx;
}

.stat-value {
  font-size: 24rpx;
  color: #666;
}

.empty-state {
  padding: 100rpx 0;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
}

.empty-image {
  width: 200rpx;
  height: 200rpx;
  margin-bottom: 30rpx;
}

.empty-text {
  font-size: 28rpx;
  color: #999;
  margin-bottom: 30rpx;
}

.reset-button {
  background-color: #FF69B4;
  color: #fff;
  font-size: 28rpx;
  padding: 10rpx 40rpx;
  border-radius: 40rpx;
}

.load-more {
  text-align: center;
  padding: 20rpx 0;
}

.load-more-text {
  font-size: 28rpx;
  color: #666;
}

.loading-text {
  font-size: 28rpx;
  color: #999;
}

.bottom-tip {
  text-align: center;
  padding: 20rpx 0;
}

.bottom-tip-text {
  font-size: 24rpx;
  color: #999;
}
</style>
